package com.board.controller;


import cn.hutool.core.bean.BeanUtil;
import com.board.dto.UserDto;
import com.board.dto.UserInfoDto;
import com.board.form.LoginByPassFrom;
import com.board.param.LoginByPassParam;
import com.board.service.UserInfoService;
import com.board.util.JwtUtil;
import com.board.util.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小叶
 * @since 2024年04月08日
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户密码登录
     * 获取ip地址生成登录日志
     */
    @ApiOperation("用户密码登录")
    @PostMapping("/loginByPass")
    public Result LoginByPass(@RequestBody LoginByPassFrom from,
                              HttpServletRequest request, HttpServletResponse response)throws Exception{
        LoginByPassParam param = BeanUtil.toBean(from, LoginByPassParam.class);
        UserInfoDto userInfo=userInfoService.loginByPass(param,request);
        HashMap<String, Object> map = new HashMap<>();
        map.put("subject", userInfo.getUserId());
        map.put("role", "用户");
        String accessToken = JwtUtil.createToken(map, 60*24);
        String refreshToken = JwtUtil.createToken(map, 24 * 60 * 3);
        response.setHeader("token", accessToken);
//        redisUtil.set(accessToken, refreshToken, 24 * 60 * 60 * 3);
        response.setHeader("Access-Control-Expose-Headers", "token");
        return Result.success("登录成功",userInfo);
    }


    //根据用户id查询用户信息
    @GetMapping("/findUserById")
    @ApiOperation("根据用户id查询用户信息")
    public Result<UserDto> findUserById(Integer userId){
        UserDto dto= userInfoService.findUserById(userId);
        return Result.success("查询成功",dto);
    }


}

